package com.maben.util;

import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyResponseUtil {
    /**
     * 统一处理没有token的返回请求
     */
    public static void handleNotLoginException(HttpServletRequest request, HttpServletResponse response)throws IOException {
        // 判断是否为 AJAX 请求
        boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        if (isAjax) {
            // AJAX 请求返回 JSON
            response.setContentType("application/json;charset=UTF-8");
            // token 无效，返回 401 状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(SaResult.notLogin().setData("登录已过期，请重新登录")));
        } else {
            // 普通请求重定向到登录页
            response.sendRedirect("/");
        }
    }
}
